package tpdisenio2009.model.dao;

import java.io.Serializable;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Projections;
import tpdisenio2009.model.HibernateUtils;


public abstract class AbstractDAO<E> {

    // Type Erasure
    public abstract Class<E> getPersistentClass();

    public int count() {
        Criteria countCriteria = HibernateUtils.getCurrentSession().createCriteria( getPersistentClass() );
        countCriteria.setProjection( Projections.rowCount());
        return ((Integer) countCriteria.uniqueResult()).intValue();
    }

    public E getById( Serializable id ) {
        return (E) HibernateUtils.getCurrentSession().load( getPersistentClass(), id );
    }

    public List<E> getAll() {
        return (List<E>) HibernateUtils.getCurrentSession().createCriteria( getPersistentClass() ).list();
    }

    public void insert( E bean) throws HibernateException {
        Session session = HibernateUtils.openSession();
        Transaction transaction = session.getTransaction();
        transaction.begin();
        try {
            session.persist( bean );
            transaction.commit();
        } catch(HibernateException ex) {
            transaction.rollback();
            throw ex;
        } finally {
            session.close();
        }
    }

    public void delete( E bean ) throws HibernateException {
        Session session = HibernateUtils.openSession();
        Transaction transaction = session.getTransaction();
        transaction.begin();
        try {
            session.delete( bean );
            transaction.commit();
        } catch(HibernateException ex) {
            transaction.rollback();
            throw ex;
        } finally {
            session.close();
        }
    }

    public void deleteById( Serializable id ) throws HibernateException {
        Session session = HibernateUtils.openSession();
        Transaction transaction = session.getTransaction();
        transaction.begin();
        try {
            E bean = getById( id );
            session.delete( bean );
            transaction.commit();
        } catch(HibernateException ex) {
            transaction.rollback();
            throw ex;
        } finally {
            session.close();
        }
    }

    public void update( E bean ) throws HibernateException {
        Session session = HibernateUtils.openSession();
        Transaction transaction = session.getTransaction();
        transaction.begin();
        try {
            session.merge( bean );
            transaction.commit();
        } catch(HibernateException ex) {
            transaction.rollback();
            throw ex;
        } finally {
            session.close();
        }
    }

}
